<template>
  <div class="user-edit-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>编辑用户</h1>
      <div class="action-buttons">
        <el-button @click="handleGoBack">
          <el-icon><ArrowLeft /></el-icon> 返回列表
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon> 保存
        </el-button>
        <el-button @click="resetForm">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
      </div>
    </div>

    <!-- 表单卡片 -->
    <el-card class="form-card">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="formRules"
        label-width="120px"
        class="user-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <h2 class="section-title">基本信息</h2>
          <el-divider></el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" disabled></el-input>
              <div class="form-hint">用户名不可修改</div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" clearable type="email"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="userForm.roleId" placeholder="请选择角色">
                <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="userForm.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 密码设置区域 -->
        <div class="form-section">
          <h2 class="section-title">密码设置</h2>
          <el-divider></el-divider>
          <div class="form-hint mb-20">若不修改密码，请保持以下密码字段为空</div>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="新密码" prop="password">
              <el-input
                v-model="userForm.password"
                placeholder="请输入新密码"
                type="password"
                show-password
              ></el-input>
              <div class="form-hint">密码长度至少8位，包含字母和数字</div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="userForm.confirmPassword"
                placeholder="请确认新密码"
                type="password"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他信息区域 -->
        <div class="form-section">
          <h2 class="section-title">其他信息</h2>
          <el-divider></el-divider>
        </div>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ArrowLeft,
  Check,
  Refresh
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

// 路由实例
const router = useRouter();
const route = useRoute();

// 表单引用
const userFormRef = ref<any>(null);

// 表单数据
const userForm = reactive({
  id: '',
  username: '',
  name: '',
  email: '',
  phone: '',
  roleId: '',
  status: '1',
  password: '',
  confirmPassword: '',
  remark: ''
});

// 角色列表
const roles = ref<any[]>([]);

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度2-20位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length < 8) {
          callback(new Error('密码长度至少8位'));
        } else if (value && !/^(?=.*[A-Za-z])(?=.*\d).+$/.test(value)) {
          callback(new Error('密码必须包含字母和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (userForm.password && value !== userForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 返回列表
const handleGoBack = () => {
  router.push({ name: 'UserList' });
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate();

    // 确认提交
    await ElMessageBox.confirm('确定要保存用户信息的修改吗？', '保存确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    // 模拟API请求
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('用户信息更新成功');
      router.push({ name: 'UserDetail', params: { id: userForm.id } });
    }, 1000);
  } catch (error) {
    // 表单验证失败或用户取消提交
    if (error !== 'cancel') {
      console.error('表单提交失败:', error);
    }
  }
};

// 重置表单
const resetForm = () => {
  getuserDetail();
};

// 获取角色列表
const getRoles = () => {
  // 模拟角色数据
  roles.value = [
    { id: '1', name: '超级管理员' },
    { id: '2', name: '财务管理员' },
    { id: '3', name: '采购管理员' },
    { id: '4', name: '普通用户' }
  ];
};

// 获取用户详情
const getuserDetail = () => {
  // 显示加载中
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 模拟API请求
  setTimeout(() => {
    const userId = route.params.id as string;
    const roleOptions = [
      { id: '1', name: '超级管理员' },
      { id: '2', name: '财务管理员' },
      { id: '3', name: '采购管理员' },
      { id: '4', name: '普通用户' }
    ];
    const randomRole = roleOptions[Math.floor(Math.random() * roleOptions.length)];
    const isEnabled = Math.random() > 0.2;

    // 设置表单数据
    Object.assign(userForm, {
      id: userId,
      username: `user${userId.replace('U', '')}`,
      name: `用户${userId.replace('U', '')}`,
      email: `user${userId.replace('U', '')}@example.com`,
      phone: `138${Math.floor(Math.random() * 100000000)}`,
      roleId: randomRole.id,
      status: isEnabled ? '1' : '0',
      remark: '这是用户的备注信息，可以在这里添加关于用户的额外说明。'
    });

    // 关闭加载
    loading.close();
  }, 800);
};

// 页面加载时初始化
onMounted(() => {
  getRoles();
  getuserDetail();
});
</script>

<style scoped lang="scss">
.user-edit-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.user-form {
  padding: 10px 0;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.mb-20 {
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-edit-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .el-col {
    &.lg-12 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}
</style>